package com.jz.digital.base;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.Window;

import com.jz.digital.R;
import com.jz.digital.dialog.WaitingDialog;
import com.jz.digital.utils.ObjectUtil;
import com.jz.digital.utils.ScreenUtil;
import com.jz.digital.utils.StatusBarsUtil;
import com.jz.digital.utils.eventbus.EventBusHelper;
import com.jz.digital.utils.eventbus.EventBusWrapper;
import com.jz.digital.utils.eventbus.IHandlerEventBus;
import com.jz.digital.view.CommonTitleBarHelper;

/**
 * @author: ym
 * @package: com.ido.veryfi.base
 * @description: ${TODO}{ 所有Activity的超类}
 * @date: 2018/7/16 0016
 * <p>
 * 必须实现的方法
 * 布局文件{@link #getLayoutResId}
 * 初始化数据方法{@link #initData}
 * 封装了标题管理类{@link CommonTitleBarHelper}
 * 注册了EventBus {@link EventBusHelper}
 * 注册了ButterKnife
 * 封装了权限请求相关方法 {@link #checkSelfPermission(String)#requestPermissions(Integer, String)#requestPermissionsSuccess(Integer)#requestPermissionsFail(Integer)}
 * 封装了toast弹出方法 {@link #showToast}
 * <p>
 * <p>
 * 如果是动态加载的布局，则可以复写调用 {@link #initViews}方法初始化控件
 * 如果需要处理EventBus的消息 则复写handleMessage
 * <p>
 * 若要使用MVP模式，
 * 子类如果有多个泛型，则第一个泛型必须是BasePresenter的子类
 * 初始化时会自动实例化第一个泛型对象，赋值给属性 mPresenter {@link #mPresenter}并且自动绑定和解绑该类
 * 并且该类需实现{@link IBaseView}接口，或者{@link IBaseView}接口的子接口
 * @see BasePresenter
 */
public abstract class BaseActivity<P extends BasePresenter> extends BaseCoreActivity implements IBaseView,
        IHandlerEventBus {

    protected P mPresenter;
    /**
     * 通用头部辅助类
     */
    protected CommonTitleBarHelper mTitleBar;
    EventBusWrapper mEventBus;
    protected WaitingDialog mWaitingDialog;
    private long mDialogShowTime;

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        viewCreate();
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        viewCreate();
    }

    /**
     * View创建完成
     */
    protected void viewCreate() {
        mTitleBar = new CommonTitleBarHelper();
        mTitleBar.init(this);
        if (isFunctionActivity()) {
            //设置titleBar颜色
            mTitleBar.setBarBackground(R.color.color_F9F9F9);
            //设置状态栏颜色
            setStatusBarColor(getColor(R.color.color_F9F9F9), true);
        } else {
            if (isStatusBgWhite()) setStatusBarColor(Color.WHITE);
            else setStatusBarColor(Color.TRANSPARENT);
        }
        StatusBarsUtil.setStatusTextColor(this, isStatusBgWhite());
    }

    @Override
    public void actionBeforeSetContentView() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        if (needEventBus()) {
            mEventBus = new EventBusWrapper();
            mEventBus.register(this);
        }
        initPresenter();
        ScreenUtil.setImmersiveStatusBar(this);
    }

    /**
     * 是否是功能页面
     */
    protected boolean isFunctionActivity() {
        return false;
    }

    @Override
    public void setTitle(int titleId) {
        mTitleBar.setTitle(titleId);
    }

    @Override
    public void setTitle(CharSequence titleId) {
        mTitleBar.setTitle((String) titleId);
    }

    /**
     * 设置沉浸式状态栏
     * 这个方法只适用于使用公共标题的情况下，个人情况下需要重新该方法
     * 如果不需要设置沉浸式，则此方法必须覆盖
     */
    protected void setNavigationBar() {
        ScreenUtil.setNavigationBar(this, getResources().getDimension(R.dimen.common_tittle_height));
    }

    /**
     * 子类如需处理EventBus发送的消息，重写此方法
     *
     * @param message 消息内容
     */
    @Override
    public void handleMessage(BaseMessage message) {
    }
    /**
     *主题色变更
     */
    protected void onThemeChange(boolean isChange) {

    }
    /**
     * 表示是否需要注册EventBus
     */
    protected boolean needEventBus() {
        return true;
    }

    /**
     * 初始化P类型的对象，并且绑定该IBaseView子类
     */
    protected void initPresenter() {
        mPresenter = autoCreatePresenter();
        if (mPresenter != null) {
            try {
                mPresenter.attachView(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 生成P类型的一个实例
     *
     * @return P类型的一个实例
     */
    public P autoCreatePresenter() {
        return ObjectUtil.getParameterizedType(getClass());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mEventBus != null) mEventBus.unregister();
        if (mPresenter != null) {
            mPresenter.detachView();
            mPresenter = null;
        }
        dismissLoadingDialog(true);
    }

    /**
     * 加载的弹框
     *
     * @param msg
     */
    public void showLoadingDialog(String msg) {
        showLoadingDialog(msg, true);
    }

    public void showLoadingDialog() {
        showLoadingDialog(null);
    }

    public void showLoadingDialog(boolean cancelable) {
        showLoadingDialog(null, cancelable);
    }

    public void showLoadingDialog(String msg, boolean cancelable) {
        try {
            if (mWaitingDialog != null && mWaitingDialog.isDialogShowing()) {
                return;
            }
            mDialogShowTime = System.currentTimeMillis();
            mWaitingDialog = WaitingDialog.newInstance(msg, cancelable);
            mWaitingDialog.show(getSupportFragmentManager());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 带背景的加载动画
     *
     * @param msg
     * @param cancelable
     * @param drawable
     */
    protected void showLoadingDialog(String msg, boolean cancelable, Drawable drawable) {
        if (mWaitingDialog != null && mWaitingDialog.isDialogShowing()) {
            return;
        }
        mDialogShowTime = System.currentTimeMillis();
        mWaitingDialog = WaitingDialog.newInstance(msg, cancelable);
        mWaitingDialog.show(getSupportFragmentManager());
        mWaitingDialog.setBackgroundDrawable(drawable);
    }

    /**
     * 弹框消失
     * 如果弹框从现实到消失时长不足1秒，则延迟0.5秒再消失
     * 否则会出现弹框闪烁一下的效果，体验不好
     *
     * @param force 是否立即隐藏loadingDialog
     */
    public void dismissLoadingDialog(boolean force) {
        if (mWaitingDialog != null && mWaitingDialog.isAdded()) {
            try {
                if (force) {
                    mWaitingDialog.dismissAllowingStateLoss();
                    mWaitingDialog = null;
                } else {
                    long timeMillis = System.currentTimeMillis();
                    if (timeMillis - mDialogShowTime < 1000 && timeMillis - mDialogShowTime > 100) {
                        getWindow().getDecorView().postDelayed(() -> {
                            if (mWaitingDialog != null) {
                                mWaitingDialog.dismissAllowingStateLoss();
                                mWaitingDialog = null;
                            }
                        }, 500);
                    } else {
                        if (mWaitingDialog != null) {
                            mWaitingDialog.dismissAllowingStateLoss();
                            mWaitingDialog = null;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                mWaitingDialog = null;
            }
        }
    }
}
